package com.itheima.service.impl;

import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * UserServiceImpl
 *
 * @author jjh
 * @date 2020/2/22
 **/
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductDao productDao;

    /**
     * 查询商品信息
     * @param pid   商品ID
     * @return
     */
    @Override
    public Product findByPid(Integer pid) {
        return productDao.findById(pid).orElseThrow(() -> new RuntimeException("未找到该商品"));
    }

    /**
     * 保存商品
     * @param p
     */
    @Transactional
    @Override
    public void save(Product p) {
        Product product = new Product();
        product.setName("Ryzen 3990X");
        product.setPrice(4000d);
        product.setStock(100);
        product.setContent("Ryzen Threadripper 3990X是一枚64核128线程的处理器,其基于Zen 2架构,使用MCM封装形式,频率方面,基础频率为2.9GHz,最高加速频率可以到4.3GHz。");
        productDao.save(product);
    }

    /**
     * 扣库存
     * @param pid 商品ID
     * @param number 减少的库存
     */
    @Transactional
    @Override
    public void reduce(Integer pid, Integer number) {
        Product product = productDao.findById(pid).orElseThrow(() -> new RuntimeException("未找到该商品"));
        product.setStock(product.getStock() - number);

        int i = 1/0;

        productDao.save(product);
    }
}
